package com.hengpeng.itfints.controller.member;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.BindCardRequest;
import com.hengpeng.itfinbase.message.partner.CashRequestMsg;
import com.hengpeng.itfinbase.message.partner.ModifyRequest;
import com.hengpeng.itfinbase.message.partner.NotifyRequestMsg;
import com.hengpeng.itfinbase.message.partner.NotifyResponseMsg;
import com.hengpeng.itfinbase.message.partner.OpenRequestMsg;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfints.constants.PartnerUtil;
import com.hengpeng.itfints.controller.BaseController;
import com.hengpeng.itfints.tools.JsonUtils;

@Controller
public class UserInfoController extends BaseController {
    protected Log logger = LogFactory.getLog(this.getClass());

    /**
     * <pre>
     * 汇付开户
     * </pre>
     * 
     * @param request
     * @param memberId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/member_operate/openRequest", method = RequestMethod.POST)
    public void open(HttpServletRequest request, HttpServletResponse res,
            @RequestParam(value = "memberId", required = false) String memberId,
            @RequestParam("cardNumber") String cardNumber, @RequestParam("realName") String realname) throws Exception {
//        ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
        OpenRequestMsg reqMsg = new OpenRequestMsg();
        UserInfo m = getSessionMember(request).getUser();
        reqMsg.setUserId(String.valueOf(m.getId()));
        reqMsg.setCardNumber(cardNumber);
        reqMsg.setEmail(m.getEmail().trim());
        reqMsg.setMobile(m.getMobile().trim());
        reqMsg.setRealName(realname);
        reqMsg.setMerPriv(String.valueOf(m.getId()));
        reqMsg.setPartnerTransType(PartnerTransType.UserRegister);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
        ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
        String htmlString = response.getOrderFormContent();
        res.setCharacterEncoding("UTF-8");
        res.setContentType("text/html");
        res.getWriter().write(htmlString);
        // js document.write 会发生乱码问题，这边采用输出流输出到页面，同步提交到汇付
        // result.setReturnValue(response);
        // return result;
    }

    /**
     * <pre>
     * 页面返回
     * </pre>
     * 
     * @param map
     * @param request
     * @param response
     * @param providerId
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/pgNotify")
    public String pgNotify(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        NotifyRequestMsg requestMessage = new NotifyRequestMsg();
        requestMessage.setIsBgNotify(false);
        requestMessage.setTransType(TransCodeConstants.PartnerTransCode.NOTIFY);
        StringBuffer parameterStr = new StringBuffer();
        Map<String, String> parameterMap = new HashMap<String, String>();
        Enumeration<String> params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String paramName = params.nextElement();
            parameterStr.append("&" + paramName + "=" + URLDecoder.decode(request.getParameter(paramName), "utf-8"));
            parameterMap.put(paramName, URLDecoder.decode(request.getParameter(paramName), "utf-8"));
        }
        if (parameterStr.length() > 0) {
            parameterStr.delete(0, 1);
        }
        requestMessage.setParamString(JsonUtils.createGson().create().toJson(parameterMap));
        requestMessage.setParameter(parameterMap);
        logger.info("第三方页面返回参数{" + parameterStr.toString() + "}");
        NotifyResponseMsg port_result = (NotifyResponseMsg) serviceFactory.getProtFactory().remoteTrans(requestMessage);
        refreshSessionMember(request);
        map.put("resultObj", port_result);
        return "/page/common_page_result.jsp";
    }

    /**
     * <pre>
     * 服务端响应
     * </pre>
     * 
     * @param map
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/bgNotify")
    public void bgNotify(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        NotifyRequestMsg requestMessage = new NotifyRequestMsg();
        requestMessage.setIsBgNotify(true);
        requestMessage.setTransType(TransCodeConstants.PartnerTransCode.NOTIFY);
        Map<String, String> parameter = new HashMap<String, String>();
        Enumeration<String> params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String paramName = params.nextElement();
            parameter.put(paramName, request.getParameter(paramName));
        }
        requestMessage.setParamString(JsonUtils.createGson().create().toJson(parameter));
        requestMessage.setParameter(parameter);
        logger.info("第三方后台通知参数{" + parameter.toString() + "}");
        NotifyResponseMsg port_result = (NotifyResponseMsg) serviceFactory.getProtFactory().remoteTrans(requestMessage);
        refreshSessionMember(request);
        map.put("param", port_result.getReturnNotifyParamValue());
        if (port_result.getRespCode().equalsIgnoreCase(RespCodeConstants.CommonCode.TRANS_SUC)) {
            response.getWriter().print(port_result.getReturnNotifyParamValue());
        }
    }

    /**
     * <pre>
     * 提现
     * </pre>
     * 
     * @param request
     * @param money
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/member_operate/draw", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult<ResponseMessage> draw(HttpServletRequest request, String money)
            throws Exception {
        UserInfo m = getSessionMember(request).getUser();
        ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
        Account account = serviceFactory.getAccountService().getAccount(m.getId());
        BigDecimal availableBalance = (new BigDecimal(account.getBaseMoney()-account.getFreezeMoney())).divide(new BigDecimal("100"),2,BigDecimal.ROUND_HALF_UP);
        if ((availableBalance.subtract(new BigDecimal(StringUtils.isEmpty(money) ? "0" : money)))
                .compareTo(new BigDecimal("2")) == -1) {
            result.setIsSuccess(false);
            result.setMessage("由于提现需要手续费2元，您最多提现:" + (availableBalance.doubleValue() - 2) + "元");
            result.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return result;
        }
        
        CashRequestMsg reqMsg = new CashRequestMsg();
        reqMsg.setUserId(m.getId());
        reqMsg.setTransAmt(money);
        reqMsg.setPartnerTransType(PartnerTransType.Cash);
        reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
        result.setReturnValue(response);
        if (!validateObjectsNullOrEmpty(response)) {
            result.setMessage(response.getRespDesc());
            result.setCode(response.getRespCode());
            if (response.getRespCode().equalsIgnoreCase(RespCodeConstants.CommonCode.TRANS_SUC)) {
                result.setIsSuccess(true);
            } else {
                result.setIsSuccess(false);

            }
        } else {
            result.setMessage("请求出错，请重试！");
            result.setIsSuccess(false);
            result.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            logger.info("提现请求出错，返回null");
        }
        result.setReturnObject(PartnerUtil.isTrustPattern());
        refreshSessionMember(request);
        return result;
    }

    /**
     * <pre>
     * 绑卡
     * </pre>
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/member_operate/bindCard", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult<ResponseMessage> bindCard(HttpServletRequest request) throws Exception {
        ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
        ResponseMessage response = new ResponseMessage();
        if (!PartnerUtil.isTrustPattern()) {
            response.setOrderFormContent("/memberCenter/addUserBankCard.htm");
            result.setReturnValue(response);
        } else {
            BindCardRequest reqMsg = new BindCardRequest();
            UserInfo m = getSessionMember(request).getUser();
            reqMsg.setUserId(m.getId());
            reqMsg.setUsrCustId(m.getTrustAccountId());
            reqMsg.setPartnerTransType(PartnerTransType.UserBindCard);
            reqMsg.setBgRetUrl(service_notify_url);
            reqMsg.setRetUrl(page_return_url);
            reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
            response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
            result.setReturnValue(response);
        }
        return result;
    }

    /**
     * 用户到第三方修改资料
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/member_operate/modifyToPartner", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult<ResponseMessage> modifyToPartner(HttpServletRequest request) throws Exception {
        ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
        ModifyRequest reqMsg = new ModifyRequest();
        UserInfo m = getSessionMember(request).getUser();
        reqMsg.setPartnerTransType(PartnerTransType.AcctModify);
        reqMsg.setUsrCustId(m.getTrustAccountId());
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
        ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
        result.setReturnValue(response);
        return result;
    }
}
